<template>
  <div class="refund-apply">
    <el-form :inline="true" :model="formData" label-width="100px" label-position="right">
      <el-form-item label="退款订单编号">
        <el-input @change="searchOrder" placeholder="退款订单编号" v-model="formData.sn" size="small" clearable></el-input>
      </el-form-item>
      <el-form-item label="申请人手机号">
        <el-input @change="searchOrder" :maxlength="11" placeholder="申请人手机号" v-model="formData.mobile" size="small"
          clearable></el-input>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select @change="searchOrder" size="small" v-model="formData.status" clearable>
          <el-option v-for="(item, index) in orderlist" :key="index" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请退款日期">
        <el-date-picker v-model="formData.refundDate" @change="searchOrder" size="small"
          value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" :default-time="['00:00:00', '23:59:59']"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click.stop="searchOrder">搜索</el-button>
      </el-form-item>
    </el-form>

    <div class="totaldata">
      <div class="left">
        <span>退款申请数：{{ applyRefundCount }}</span>
        <span>申请退款金额：{{ applyRefundSumMoney }}</span>
      </div>
      <div class="right"><el-button type="primary" size="small" @click.stop="addrefund">新增</el-button></div>
    </div>

    <el-dialog :show-close="false" :visible.sync="dialogaddrefund" width="30%" top="25vh" :close-on-click-modal="false">
      <div class="list_item">
        <div class="title">申请人手机号：</div>
        <div class="content">
          <el-input placeholder="请输入手机号" v-model="addform.mobile" size="small" clearable></el-input>
          <el-button type="primary" size="small" @click.stop="searchmobile">搜索</el-button>
        </div>
      </div>
      <div class="list_item">
        <div class="title">申请人姓名：</div>
        <div class="content">
          {{ addform.nickName }}
        </div>
      </div>
      <div class="list_item">
        <div class="title">账户余额：</div>
        <div class="content">
          {{ addform.money }}
        </div>
      </div>
      <div class="list_item list_item_t">
        <div class="title">充值赠送金额：</div>
        <div class="contentno">
          <div>{{ addform.giveMoney }}</div>
          <div class="tips" v-if="addform.giveMoney">
            退款成功后赠送金额会清零
          </div>
        </div>
      </div>
      <div class="list_item">
        <div class="title">可退金额：</div>
        <div class="content">
          {{ addform.refundMoney }}
        </div>
      </div>
      <div class="list_item">
        <div class="title">本次退款金额：</div>
        <div class="content">
          <el-input placeholder="请输入金额" @input="controlipt" v-model="iptrefundMoney" size="small" clearable></el-input>
          <span style="margin-left:-10px;">元</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:left;">
        <el-button type="primary" size="medium" @click="addconfirm">确 定</el-button>
        <el-button size="medium" @click="addcancel">取 消</el-button>
      </div>
    </el-dialog>

    <avue-crud ref="crud" :page="page" :data="dataList" :table-loading="dataListLoading" :option="tableOption"
      @size-change="sizeChange" @current-change="currentChange">
      <template slot-scope="scope" slot="orderNo">
        <div><span>{{ scope.row.sn }}</span></div>
      </template>
      <template slot-scope="scope" slot="basicinfo">
        <div><span>姓名：{{ scope.row.nickName }}</span></div>
        <div><span>手机号：{{ scope.row.mobile }}</span></div>
      </template>
      <template slot-scope="scope" slot="basicdate">
        <div><span>{{ scope.row.refundDate }}</span></div>
      </template>
      <template slot-scope="scope" slot="refundamount">
        <div><span>{{ scope.row.applyRefundMoney }}</span></div>
      </template>
      <template slot-scope="scope" slot="actualrefundamount">
        <div><span>{{ scope.row.money }}</span></div>
      </template>
      <template slot-scope="scope" slot="balance">
        <div><span>{{ Number(scope.row.applyRefundMoney) - Number(scope.row.money) }}</span></div>
      </template>
      <template slot-scope="scope" slot="giftamount">
        <div><span>{{ scope.row.giveMoney }}</span></div>
      </template>
      <template slot-scope="scope" slot="type">
        <div>
          <span>{{ scope.row.status == 0 ? '待退款' : scope.row.status == 0 ? '待退款' : scope.row.status == 1 ? '全部退款成功' :
            scope.row.status == 2 ? '部分待退款' : scope.row.status == 3 ? '部分退款成功' : scope.row.status == 4 ? '取消申请' : ''
            }}</span>
        </div>
      </template>
      <template slot-scope="scope" slot="menu">
        <div class="button-container">
          <el-button class="button" type="primary" size="small" @click.stop="refunduser(scope.row)">退款至用户</el-button>
          <el-button class="button" type="danger" size="small" @click.stop="withdraw(scope.row)">取消申请</el-button>
          <el-button class="button" type="primary" size="small"
            @click.stop="checkRefundProgress(scope.row)">查看退款进度</el-button>
        </div>
      </template>
    </avue-crud>
    <el-dialog :show-close="false" :visible.sync="dialogrefundinfo" :close-on-click-modal="false">
      <div class="header">
        <div>退款订单编号：{{ refunduserinfo.sn }}</div>
        <div>申请人：{{ refunduserinfo.applyor }}</div>
        <div>手机号：{{ refunduserinfo.mobile }}</div>
        <div>申请时间：{{ refunduserinfo.createDate }}</div>
        <div>充值赠送金额：{{ refunduserinfo.giveMoney }}元</div>
        <div>申请退款金额：{{ refunduserinfo.applyRefundMoney }}元</div>
        <div>实际退款金额：{{ refunduserinfo.money }}元</div>
        <div>剩余退款金额：{{ refunduserinfo.refundMoney }}元</div>
      </div>
      <el-table :data="refunduserinfo.memberPayOrderList" border stripe :summary-method="getSummaries" show-summary
        style="width: 100%;margin-top:10px;">
        <el-table-column prop="orderNumber" width="280" label="充值订单编号">
        </el-table-column>
        <el-table-column prop="price" width="110" label="充值本金金额">
        </el-table-column>
        <el-table-column prop="payDate" label="充值时间">
        </el-table-column>
        <el-table-column prop="refundPrice" width="110" label="剩余可退金额">
        </el-table-column>
        <el-table-column width="160" label="本次退款金额">
          <template slot-scope="scope">
            <el-input @input="monitoriptrefund(scope.row)" v-model="scope.row.thisRefundPrice"
              placeholder="请输入退款金额"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div style="color:red;margin-top:10px;">温馨提示：发生退款后,充值赠送金额会清零</div>
      <div slot="footer" class="dialog-footer" style="text-align:left;">
        <el-button type="primary" size="medium" @click="confirmrefund(0)">原路退款</el-button>
        <el-button type="primary" size="medium" @click="confirmrefund(1)">线下打款</el-button>
        <el-button size="medium" @click="cancelrefund">取 消</el-button>
      </div>
    </el-dialog>
    <check-refund-progress ref="checkRefundProgress"></check-refund-progress>
  </div>
</template>

<script>
import { tableOption } from '@/crud/refund/applylist'
import checkRefundProgress from '@/views/modules/refund/checkRefundProgress'
export default {
  components: {
    checkRefundProgress
  },
  data() {
    return {
      dataListLoading: false,
      showRefundProgress: false,
      formData: {
        sn: '',
        status: '',
        mobile: '',
        refundDate: [],
        startTime: '',
        endTime: '',
      },
      orderlist: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '部分退款',
          value: 2
        },
        {
          label: '待退款',
          value: 0
        }
      ],
      dataList: [],
      applyRefundCount: '',
      applyRefundSumMoney: '',
      tableOption: tableOption,
      page: {
        total: 0, // 总条数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },

      dialogaddrefund: false,
      addform: {},
      iptrefundMoney: '',
      dialogrefundinfo: false,


      refunduserinfo: {},
    }
  },
  mounted() {
    this.getrefundapply(this.page, this.formData)
  },
  methods: {
    // 获取退款申请记录
    getrefundapply(page, params) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/v1/merchant/refund/apply/list'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              size: page == null ? this.page.pageSize : page.pageSize
            },
            params
          )
        )
      }).then(({ data }) => {
        this.applyRefundCount = data.data.applyRefundCount
        this.applyRefundSumMoney = data.data.applyRefundSumMoney
        this.page.total = data.data.memberRefundIPage.total
        this.dataList = data.data.memberRefundIPage.records
        this.dataListLoading = false
      }).catch(err => {
        console.log(err, "err")
      })
    },
    // 条件搜索
    searchOrder() {
      console.log(this.formData)
      if (this.formData.refundDate) {
        this.formData.startTime = this.formData.refundDate[0]
        this.formData.endTime = this.formData.refundDate[1]
      } else {
        this.formData.startTime = ''
        this.formData.endTime = ''
      }

      this.getrefundapply(this.page, this.formData)
    },

    // 新增退款
    addrefund() {
      this.dialogaddrefund = true
    },
    // 手机号搜索
    searchmobile() {
      if (!this.addform.mobile) {
        this.$message({
          message: '请输入手机号',
          type: 'warning'
        })
        return
      }
      this.$http({
        url: this.$http.adornUrl('/v1/merchant/refund/member'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              mobile: this.addform.mobile
            },
          )
        )
      }).then((res) => {
        console.log(res, "res")
        this.addform = JSON.parse(JSON.stringify(res.data.data))
        this.iptrefundMoney = res.data.data.refundMoney
        console.log(this.addform)
      }).catch(err => {
        this.addform = {}
        console.log(err, "err")
      })
    },
    // 控制input值大小
    controlipt(e) {
      console.log(e, "数据")
      if (Number(e) > Number(this.addform.refundMoney)) {
        this.$message({
          message: '退款金额不能大于可退金额',
          type: 'warning'
        });
        this.iptrefundMoney = this.addform.refundMoney
      }
    },
    // 取消
    addcancel() {
      this.addform = {}
      this.iptrefundMoney = ''
      this.dialogaddrefund = false
    },
    // 添加确认按钮
    addconfirm() {
      console.log(this.addform)
      // console.log(this.iptrefundMoney)
      if (!this.addform.mobile) {
        this.$message({
          message: '请输入手机号',
          type: 'warning'
        })
        return
      }
      this.$http({
        url: this.$http.adornUrl('/v1/merchant/refund/add/apply'),
        method: 'post',
        data: this.$http.adornData({
          actualMoney: this.iptrefundMoney,
          id: this.addform.id
        })
      }).then((res) => {
        console.log(res, "res")
        this.dialogaddrefund = false
        this.addform = {}
        this.iptrefundMoney = ''
        this.getrefundapply(this.page, this.formData)
      }).catch(err => {
        this.addform = {}
        console.log(err, "err")
      })
    },

    // 退款至用户
    refunduser(val) {
      this.dialogrefundinfo = true
      this.$http({
        url: this.$http.adornUrl('/v1/merchant/refund/get/pay/order'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              id: val.id
            },
          )
        )
      }).then((res) => {
        console.log(res, "res")
        this.refunduserinfo = res.data.data
      }).catch(err => {
        console.log(err, "err")
      })
      console.log(val)
    },
    // 取消退款
    cancelrefund() {
      this.refunduserinfo = {}
      this.dialogrefundinfo = false
    },
    // 确认退款
    confirmrefund(method) {
      console.log(this.refunduserinfo.memberPayOrderList)
      let memberPayOrderList = []
      this.refunduserinfo.memberPayOrderList.map(i => {
        if (i.thisRefundPrice) {
          memberPayOrderList.push(i)
        }
      })
      if (method == 1) {
        this.$confirm('此操作退款需人工进行退款, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/v1/merchant/refund/confirm'),
            method: 'post',
            data: this.$http.adornData({
              memberPayOrderList: memberPayOrderList,
              id: this.refunduserinfo.id,
              method: method
            })
          }).then((res) => {
            console.log(res, "res")
            if (res.data.code != 0) {
              this.$message({
                message: res.msg,
                type: 'error'
              })
              return
            } else {
              this.$message({
                message: '退款提交, 请及时处理退款订单',
                type: 'success'
              })
            }
            this.dialogrefundinfo = false
            this.refunduserinfo = {}
            this.getrefundapply(this.page, this.formData)
          }).catch(err => {
            console.log(err, "err")
          })
        }).catch(() => {

        });
      } else {
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/refund/confirm'),
          method: 'post',
          data: this.$http.adornData({
            memberPayOrderList: memberPayOrderList,
            id: this.refunduserinfo.id,
            method: method
          })
        }).then((res) => {
          console.log(res, "res")
          if (res.data.code != 0) {
            this.$message({
              message: res.msg,
              type: 'error'
            })
            return
          } else {
            this.$message({
              message: '退款成功',
              type: 'success'
            })
          }
          this.dialogrefundinfo = false
          this.refunduserinfo = {}
          this.getrefundapply(this.page, this.formData)
        }).catch(err => {
          console.log(err, "err")
        })
      }

    },
    // 取消申请
    withdraw(val) {
      console.log(val)
      this.$confirm('是否确认取消申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/v1/merchant/refund/cancel/apply'),
          method: 'post',
          data: this.$http.adornData({
            status: 4,
            id: val.id
          })
        }).then((res) => {
          console.log(res, "res")
          this.$message({
            message: '取消成功',
            type: 'success'
          })
          this.getrefundapply(this.page, this.formData)
        }).catch(err => {
          console.log(err, "err")
        })
      }).catch(() => {

      });
    },
    checkRefundProgress(row) {
      console.log("row", row)
      this.showRefundProgress = true
      console.log(row)
      this.$nextTick(() => {
        this.$refs['checkRefundProgress'].init({ id: row.id })
      })
    },

    //
    monitoriptrefund(e) {
      console.log(e.thisRefundPrice)
      console.log(e.refundPrice)
      if (Number(e.thisRefundPrice) > Number(e.refundPrice)) {
        this.$message({
          message: '退款金额不能大于剩余可退金额',
          type: 'warning'
        })
        e.thisRefundPrice = e.refundPrice
      }
    },

    getSummaries(param) {
      // console.log(param,"param")
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (index === columns.length - 1) {
          sums[index] = 0
          data.forEach(i => {
            sums[index] = sums[index] + Number(i.thisRefundPrice)
          })
          sums[index] += '元'
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },

    sizeChange(val) {
      console.log(val)
      this.page.pageSize = val
      this.getrefundapply(this.page, this.formData)
    },
    currentChange(val) {
      console.log(val)
      this.page.currentPage = val
      this.getrefundapply(this.page, this.formData)
    }
  }
}
</script>

<style lang="scss" scoped>
.totaldata {
  width: 99%;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px 10px 16px;
  background: #f3f3f3;

  .left {
    line-height: 32px;
    height: 32px;

    span {
      margin-right: 20px;
    }
  }
}

.button-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;

  /* 确保容器填满整个单元格的高度 */
  .button {
    margin-top: 10px;
  }

  /* 将第一个按钮的 margin-top 设置为 0 */
  .button:first-child {
    margin-top: 0;
  }
}

.list_item {
  display: flex;
  align-items: center;
  height: 40px;

  .title {
    width: 120px;
    text-align: right;
  }

  .content {
    display: flex;
    align-items: center;

    .el-input {
      margin-right: 20px;
    }
  }

  .contentno {
    .tips {
      color: red;
      font-size: 12px;
      margin-top: 6px;
    }
  }
}

.list_item_t {
  align-items: flex-start;
}

.header {
  margin-top: -30px;
  display: flex;
  flex-wrap: wrap;

  div {
    margin-right: 60px;
    margin-bottom: 16px;
  }
}
</style>
